<template>
  <el-tabs type="border-card">
    <el-tab-pane label="目标值设置">
      <el-date-picker
        style="float: right;"
        v-model="targetDate"
        align="right"
        type="date"
        placeholder="选择日期"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-time-select
        v-show="timeSelectShow"
        v-model="selectedTargetTime"
        :picker-options="timeSelectOptions"
        @blur="blurTimeSelect"
        @change="changeTimeSelect"
        placeholder="选择时间">
      </el-time-select>
      <el-table
        ref="singleTable"
        :data="targetData"
        height="250"
        @current-change="handleCurrentChange"
        style="width: 100%">
        <el-table-column
          prop="time"
          label="时间段">
        </el-table-column>
        <el-table-column
          label="目标值（MPa）">
          <template slot-scope="scope">
            <input type="text" v-model="scope.row.target">
          </template>
        </el-table-column>
      </el-table>
      <div class="ctrls">
        <div class="buttons">
          <el-button type="primary" @click="iconsShow = !iconsShow">修改</el-button>
          <el-button type="primary" @click="clickSave">保存</el-button>
        </div>
        <div class="icons" v-show="iconsShow">
          <el-button type="primary" icon="el-icon-plus" circle @click="clickAdd"></el-button>
          <el-button type="primary" icon="el-icon-minus" circle @click="clickMinus"></el-button>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane label="历史目标值">
      <el-date-picker
        style="float: right;"
        v-model="historyDate"
        align="right"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="changeHistoryDate"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-table
        :data="historyData"
        height="250"
        stripe
        style="width: 100%">
        <el-table-column
          prop="someday"
          label="日期"
          sortable
          width="180">
        </el-table-column>
        <el-table-column
          prop="time"
          label="时间段"
          width="180">
        </el-table-column>
        <el-table-column
          prop="target"
          label="目标值（MPa）">
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
const { ymd } = require('../../utils.js')

export default {
  props: ['historyData'],
  data() {
    return {
      // 时间选择器的显示
      timeSelectShow: false,
      // 选中的目标时间
      selectedTargetTime: '',
      iconsShow: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      targetDate: '', // 日期
      targets: [], // 设定目标值的大数组，以日期区分
      historyDate: '' // 日期
    }
  },
  computed: {
    // 获取当前再用的设置目标数据
    targetData() {
      if (!this.targetDate) return []

      const someday = ymd(this.targetDate)
      let json = this.targets.find(tds => tds.someday === someday)
      if (!json) {
        json = { someday, somedayTargets: [] }
        this.targets.push(json)
      }
      return json.somedayTargets
    },
    // 时间选择器参数
    timeSelectOptions() {
      return {
        start: this.startTime,
        step: '01:00',
        end: '24:00'
      }
    },
    // 目标数据的最后一个值
    lastTargetData() {
      return this.targetData[this.targetData.length - 1]
    },
    // 下次起始的目标时间
    startTime() {
      if (this.lastTargetData) return this.lastTargetData.time.split('-')[1]
      return '00:00'
    },
    // 检测最后一个目标数据是否有变动
    lastTargetDataIsConst() {
      const lastTargetData = this.lastTargetData
      if (lastTargetData) {
        return (
          lastTargetData.startTime.split(' ')[1] ===
          lastTargetData.endTime.split(' ')[1]
        )
      }
      return false
    }
  },
  methods: {
    // 修改了历史日期
    changeHistoryDate(dates) {
      const startTime = dates[0]
      const endTime = dates[1]
      this.$emit('changeHistoryDate', {
        startTime: ymd(startTime),
        endTime: ymd(endTime),
      })
    },
    // 时间选择器变化
    changeTimeSelect(time) {
      this.lastTargetData.time = `${this.lastTargetData.time.replace(/.{5}$/, time)}`
      this.lastTargetData.endTime = `${ymd(this.targetDate)} ${this.lastTargetData.time.slice(6)}`
    },
    // 时间选择器失去焦点
    blurTimeSelect() {
      this.timeSelectShow = false
    },
    // 点击行事件
    handleCurrentChange(row, oldRow) {
      // 取消死循环，null 来自下面
      if (!row) return

      if (row === this.lastTargetData) {
        this.timeSelectShow = true
      }
      // 不要绑定选中，不设置 tag，无法绕开死循环此函数
      this.$refs.singleTable.setCurrentRow(null)
    },
    // 点击保存
    clickSave() {
      this.timeSelectShow = false
      this.iconsShow = false
      this.selectedTargetTime = '00:00'
      this.$emit('save', { targets: this.targets })
      this.targets = []
    },
    clickAdd() {
      this.timeSelectShow = false
      // 如果最后一个数据时间没有变化
      if (this.lastTargetDataIsConst) {
        alert('请修改最后一个数据再添加。')
        return
      }
      if (!this.targetDate) {
        alert('请选择一个日期再继续。')
        return
      }
      const day = ymd(this.targetDate)
      this.targetData.push({
        startTime: `${day} ${this.startTime}`,
        endTime: `${day} ${this.startTime}`,
        time: `${this.startTime}-${this.startTime}`,
        target: '100'
      })
    },
    clickMinus() {
      this.timeSelectShow = false
      this.targetData.pop()
      this.selectedTargetTime = this.startTime
    }
  }
}
</script>

<style scoped lang='less'>
.ctrls {
  position: relative;
  display: flex;
  justify-content: flex-end;
  .icons {
    position: absolute;
    bottom: 50px;
    right: 20px;
  }
}
</style>
